<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>proxy</title>
  </head>
  <body>
    <script>
      let handlers = new Map();
      let reactivites = new Map();
      let usedReactivitys = [];
      let obj = {
        a: {
          x: 1,
        },
        b: 2,
      };
      function reactive(object) {
        if (reactivites.has(object)) {
          return reactivites.get(object);
        }
        let proxy = new Proxy(object, {
          get(obj, prop) {
            usedReactivitys.push([obj, prop]);
            if (typeof obj[prop] === "object") {
              return reactive(obj[prop]);
            }
            return obj[prop];
          },
          set(obj, prop, val) {
            obj[prop] = val;
            if (handlers.get(obj)) {
              if (handlers.get(obj).get(prop)) {
                for (let handler of handlers.get(obj).get(prop)) {
                  handler();
                }
              }
            }
            return obj[prop];
          },
        });

        reactivites.set(object, proxy);
        reactivites.set(proxy, proxy);
        return proxy;
      }

      function effect(handler) {
        usedReactivitys = [];
        handler();
        console.log(usedReactivitys);
        for (let usedReactivity of usedReactivitys) {
          let [obj, prop] = usedReactivity;
          console.log([obj, prop]);
          if (!handlers.has(obj)) {
            handlers.set(obj, new Map());
          }
          if (!handlers.get(obj).has(prop)) {
            handlers.get(obj).set(prop, []);
          }
          handlers.get(obj).get(prop).push(handler);
        }
      }

    //   let dummy;
    //   let proxy = reactive(obj);

      //   effect(() => (dummy = proxy.a));
      //   console.log(dummy);
      //   proxy.a = 2;
      //   console.log(dummy);
      let v;
      let p = reactive(obj);
      effect(() => (v = p.a.x));
      console.log(v);
      p.a = { x: 10 };
      console.log(v);
    </script>
  </body>
</html>
